package cn.edu.scau.cmi.huangxiyan.hibernate.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.edu.scau.cmi.huangxiyan.hibernate.domain.Teacher;
import cn.edu.scau.cmi.huangxiyan.hibernate.unit.SessionFactoryUnit;

public class TeacherDAO {
	private Session session = null;

	private Session getSession() {
		if (session == null) {
			session = SessionFactoryUnit.getSession();
		}

		return session;
	}

	public boolean save(Teacher teacher) {
		Transaction ts = getSession().beginTransaction();

		try {
			getSession().save(teacher);
			ts.commit();

			return true;
		} catch (Exception e) {
			throw e;
		}
	}

	public boolean update(Teacher teacher) {
		Transaction ts = getSession().beginTransaction();

		try {
			getSession().update(teacher);
			ts.commit();

			return true;
		} catch (Exception e) {
			throw e;
		}
	}

	public boolean delete(Teacher teacher) {
		Transaction ts = getSession().beginTransaction();

		try {
			getSession().delete(teacher);
			ts.commit();

			return true;
		} catch (Exception e) {
			throw e;
		}
	}

	public List<?> findAll() {
		try {
			Query q = getSession().createQuery("from Teacher");

			return q.list();
		} catch (Exception e) {
			return null;
		}
	}

	public List<?> findByName(Object name) {
		try {
			String queryString = "from Teacher as model where model." + "name" + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, name);

			return queryObject.list();
		} catch (RuntimeException re) {
			return null;
		}
	}

}
